package com.ebeitech.auction.view.auction;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ebeitech.auction.R;
import com.ebeitech.auction.bean.Auction;
import com.ebeitech.auction.bean.AuctionBid;
import com.ebeitech.auction.bean.AuctionPhase;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.domain.ChatMessage;
import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.model.AuctionPhaseModel;
import com.ebeitech.auction.http.service.HttpAuctionServiceRx;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/11/1.
 */
public class AuctionRecordFragment extends Fragment {

	@BindView(R.id.listView)
	ListView mListView;
	Unbinder unbinder;

	private Context mContext;
	private BaseAdapter mAdapter;
	private List<AuctionPhase> mAuctionPhases = new ArrayList<AuctionPhase>();
	private List<AuctionBid> mAuctionBids = new ArrayList<AuctionBid>();

	private Auction mAuction;

	private String mState;

	private View convertView;

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(intent.getAction())) {
					ChatMessage chatMessage = (ChatMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
					if (chatMessage != null) {

						if (ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL.equals(chatMessage.getMessageType())
								||ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
								||ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(chatMessage.getMessageType())) {
							if (!CommonConstants.STATE_PUBLISHED.equals(mState)) {
								loadData(false);
							}
							else {
								convertView.findViewById(R.id.view_auction_info).setVisibility(View.VISIBLE);
								convertView.findViewById(R.id.view_not_begin).setVisibility(View.GONE);
								convertView.findViewById(R.id.view_top).setVisibility(View.GONE);
								convertView.findViewById(R.id.view_bottom).setVisibility(View.GONE);
								loadData(false);
							}
						}
					}
				}
			}
		}
	};

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		convertView = inflater.inflate(R.layout.ebei_view_auction_live, null);
		unbinder = ButterKnife.bind(this, convertView);
		mContext = getActivity();

		Intent intent = getActivity().getIntent();
		if (intent != null) {
			mAuction = (Auction) intent.getSerializableExtra(CommonConstants.AUCTION);
		}

		initView(convertView);
		registerBroadCast();
		return convertView;
	}

	private void initView(View view) {
		mAdapter = new LandInfoAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setDivider(null);
		mState = mAuction.getStateCode();
		if (CommonConstants.STATE_PUBLISHED.equals(mState)) {
			// 如果房间未开始,就没必要加载记录
			view.findViewById(R.id.view_auction_info).setVisibility(View.GONE);
			view.findViewById(R.id.view_not_begin).setVisibility(View.VISIBLE);
		} else {
			view.findViewById(R.id.view_auction_info).setVisibility(View.VISIBLE);
			view.findViewById(R.id.view_not_begin).setVisibility(View.GONE);
			view.findViewById(R.id.view_top).setVisibility(View.GONE);
			view.findViewById(R.id.view_bottom).setVisibility(View.GONE);
			loadData();
		}
	}

	private void loadData() {
		loadData(true);
	}

	private void loadData(boolean isProgressDialogVisible) {
		HttpService mHttpService = HttpService.getInstance();
		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.getAuctionPhaseList(mAuction.getAuctionId());
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<AuctionPhaseModel>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
			}

			@Override
			public void onSuccess(AuctionPhaseModel result) {
				if (result == null) {
					ViewUtil.toastMsg(mContext, R.string.ebei_network_load_failure);
					return;
				}

				List<AuctionPhase> auctionPhases = result.getAuctionPhases();
				List<AuctionBid> bids = result.getBids();

				mAuctionPhases.clear();
				mAuctionBids.clear();
				if (auctionPhases != null) {
					mAuctionPhases.addAll(auctionPhases);
				}
				if (bids != null) {
					mAuctionBids.addAll(bids);
				}
				mAdapter.notifyDataSetChanged();
			}
		}, AuctionPhaseModel.class, isProgressDialogVisible);
	}

	class LandInfoAdapter extends BaseAdapter {

		private int margin;

		public LandInfoAdapter() {
			margin = ViewUtil.dp2px(mContext, 5);
		}

		@Override
		public int getCount() {
			return mAuctionBids.size();
		}

		@Override
		public Object getItem(int position) {
			return mAuctionBids.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder mViewHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_record_item, null);
				mViewHolder = new ViewHolder();
				mViewHolder.setView(convertView);
				convertView.setTag(mViewHolder);

				mViewHolder.viewContent.removeAllViews();
				LinearLayout llytRow = null;
				for (int i = 0; i < mAuctionPhases.size(); i++) {
					AuctionPhase auctionPhase = mAuctionPhases.get(i);
					if (i % 2 == 0) {
						llytRow = getNewRow();
						llytRow.setWeightSum(2);
						mViewHolder.viewContent.addView(llytRow);
						if (i > 0) {
							llytRow.setPadding(0, margin, 0, 0);
						}
					}
					LinearLayout itemView = getNewRow();
					TextView labelText = getTextView();
					labelText.setTextColor(getResources().getColor(R.color.ebei_text_common_light));
					labelText.setText(auctionPhase.getPhaseName() + ":");
					TextView valueText = getTextView();
					valueText.setTextColor(getResources().getColor(R.color.ebei_orange));
					valueText.setPadding(margin, 0, 0, 0);

					itemView.addView(labelText);
					itemView.addView(valueText);
					LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) itemView.getLayoutParams();
					lp.weight = 1;
					lp.gravity = Gravity.CENTER_VERTICAL;
					itemView.setGravity(Gravity.CENTER_VERTICAL);
					llytRow.addView(itemView);
				}

				mViewHolder.ivBidderTimes.measure(0, 0);
				ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) mViewHolder.tvBidderTimes.getLayoutParams();
				lp.height = mViewHolder.ivBidderTimes.getMeasuredWidth();
				mViewHolder.tvBidderTimes.setLayoutParams(lp);
			} else {
				mViewHolder = (ViewHolder) convertView.getTag();
			}

			AuctionBid auctionBid = mAuctionBids.get(position);
			mViewHolder.tvTime.setText(TimeUtil.getDisplayTime(auctionBid.getBidTime()));
			String code = auctionBid.getAuctionBidderCode();
			if (!StringUtil.isEmpty(auctionBid.getBidderName())) {
				code = code + " | " + auctionBid.getBidderName();
			}
			mViewHolder.tvCode.setText(code);
			mViewHolder.tvPhase.setText(auctionBid.getPhaseName());
			mViewHolder.tvBidderTimes.setText(auctionBid.getBidTimes());
			if ("-1".equals(auctionBid.getBidTimes())) {
				mViewHolder.tvBidderTimes.setText("撤");
			}

			List<AuctionPhase> bidHistories = auctionBid.getBidHistories();
			LinearLayout llytRow = null;
			int count = 0;
			for (int i = 0; i < mAuctionPhases.size(); i++) {
				AuctionPhase auctionPhase = mAuctionPhases.get(i);
				if (i % 2 == 0) {
					llytRow = (LinearLayout) mViewHolder.viewContent.getChildAt(count);
					count++;
				}
				LinearLayout itemView = (LinearLayout) llytRow.getChildAt(i % 2);
				TextView valueText = (TextView) itemView.getChildAt(1);

				String content = "";
				if (StringUtil.getDefaultString(auctionBid.getPhaseId()).equals(auctionPhase.getPhaseId())) {
					// 然后获取当前节点的当前阶段值
					content = StringUtil.getDefaultString(auctionBid.getPrice());
					content += auctionPhase.getPhaseResultRateString(auctionBid.getPriceRate());
				}else {
					for (int j = 0;j<bidHistories.size();j++)
					{

						// 先遍历bidHistories填写历史值
						AuctionPhase bidAuctionPhase = bidHistories.get(j);
						if (StringUtil.getDefaultString(bidAuctionPhase.getPhaseId()).equals(auctionPhase.getPhaseId()))
						{
							content = StringUtil.getDefaultString(bidAuctionPhase.getLastBidPrice()) + StringUtil.getDefaultString(auctionPhase.getUnit());
							content += auctionPhase.getPhaseResultRateString(bidAuctionPhase.getLastBidRate());
						}

					}
				}
				valueText.setText(content);
			}

			return convertView;
		}

		private LinearLayout getNewRow() {
			LinearLayout llytRow = new LinearLayout(mContext);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			llytRow.setOrientation(LinearLayout.HORIZONTAL);
			llytRow.setLayoutParams(lp);
			return llytRow;
		}

		private TextView getTextView() {
			TextView textView = new TextView(mContext);
			textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.ebei_common_small_text_size));
			textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
			return textView;
		}

		class ViewHolder {
			@BindView(R.id.tv_time)
			TextView tvTime;
			@BindView(R.id.tv_bidder_times)
			TextView tvBidderTimes;
			@BindView(R.id.tv_phase)
			TextView tvPhase;
			@BindView(R.id.tv_code)
			TextView tvCode;
			@BindView(R.id.view_content)
			LinearLayout viewContent;
			@BindView(R.id.iv_bidder_times)
			ImageView ivBidderTimes;
			@BindView(R.id.view_bidder_times)
			View viewBidderTimes;

			void setView(View view) {
				ButterKnife.bind(this, view);
			}
		}
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		mContext.registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
		mContext.unregisterReceiver(mBroadcastReceiver);
	}

}
